package com.blog.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blog.entity.po.ArticleTag;
import com.blog.entity.po.Tag;
import com.blog.mapper.ArticleTagMapper;
import com.blog.mapper.TagMapper;
import com.blog.service.ITagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 标签 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-24
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements ITagService {

    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Override
    public void delById(String id) {
        Tag tag = getById(id);
        if (ObjUtil.isEmpty(tag)) {
            throw new RuntimeException("标签不存在");
        }
        // 删除tag表中数据
        boolean b = removeById(id);
        if (!b) {
            throw new RuntimeException("删除失败");
        }
        // 删除article_tag表中数据
        LambdaQueryWrapper<ArticleTag> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ArticleTag::getTagId, id);
        articleTagMapper.delete(lambdaQueryWrapper);
    }

    @Override
    public void saveTag(Tag tag) {
        Tag one = lambdaQuery()
                .eq(Tag::getTagName, tag.getTagName())
                .one();
        if (!ObjUtil.isEmpty(one)) {
            throw new RuntimeException("标签已存在");
        }
        tag.setStatus(1);
        boolean b = save(tag);
        if (!b) {
            throw new RuntimeException("添加失败");
        }

    }

    @Override
    public void editTag(Tag tag) {
        Tag one = lambdaQuery()
                .eq(Tag::getTagName, tag.getTagName())
                .one();
        if (!ObjUtil.isEmpty(one) && !Objects.equals(one.getId(), tag.getId())) {
            throw new RuntimeException("标签已存在");
        }
        boolean b = updateById(tag);
        if (!b) {
            throw new RuntimeException("修改失败");
        }
    }


}
